from PyQt4.QtGui import QWidget,QVBoxLayout,QStandardItemModel,QStandardItem,QBrush,QColor,QFont,QSortFilterProxyModel
from PyQt4.QtCore import QString,Qt,QVariant
from KDataBase.KQueryDB import KQueryDB
from decimal import *
import collections
class KStocksSortItemModel(QSortFilterProxyModel):
	def __init__(self, parent=None):
		super(KStocksSortItemModel, self).__init__(parent)	
	def lessThan(self,left,right):
		if left.column()!=7 :
			return QSortFilterProxyModel.lessThan(self,left,right)
		else: #handle sorting of change ratio
			qleft=self.sourceModel().data(left,Qt.DisplayRole)
			qright=self.sourceModel().data(right,Qt.DisplayRole)
			rightval=float(str(qright.toString())[0:-2])
			leftval=float(str(qleft.toString())[0:-2])
			return leftval<rightval

class KStandardItem(QStandardItem):
	def __init__(self,text=''):
		super(KStandardItem, self).__init__(text)	

		
		
class KStocksItemModel(QStandardItemModel):
	# represent the model of stocks table: (row denotes symbol and col denots feature)
	def __init__(self, parent=None):
		super(KStocksItemModel, self).__init__(parent)	
		self.oddcolor=QBrush(QColor(0,0,0))
		self.evencolor=QBrush(QColor(0,64,0))
		self.txtfont=QFont("Times", 11)
		self.cursymbolist=[]
		
		Headers=['Symbol','Date','Open','High','Low','Close','Volumn',u'Change%']
		ActualHeaders=['name','date','open','high','low','close','volumn','percent']
		self.HeaderLabels=collections.OrderedDict()
		for each_index in range(0,len(Headers)):			
			self.HeaderLabels[Headers[each_index]]=ActualHeaders[each_index]
			


	def data(self,index,role):
		# overide
		row=index.row()
		col=index.column()
		if role==Qt.BackgroundRole:
			if row%2==0:
				return self.oddcolor
			else:
				return self.oddcolor
		elif role==Qt.FontRole:
			return self.txtfont
		else:
			return QStandardItemModel.data(self,index,role)

	def OnSetupColumns(self,HeaderLabels):
		#called when setting up columns
		self.setColumnCount(len(HeaderLabels))
		index=0
		for each_col in HeaderLabels.keys():
			self.setHeaderData(index, Qt.Horizontal,QString(each_col))
			index+=1

			
	def ColumnColor(self, curseries,colname):
		# get the column color given current panda series
		if colname in ['name','date']:
			return QColor(255,255,255)
		else:
			if curseries['open']<curseries['close']: # set color as red
				return QColor(0,255,0)
			else:
				return QColor(255,0,0)			

		
	def ColumnValue(self, curseries,colname):
		# get the column color given current panda series
		if colname=='name':
			return QString(curseries.name)
		elif colname=='date':
			return QString(str(curseries['date']))
		elif colname in ['open','high','low','close']:
			return round(curseries[colname],2)
		elif colname=='volumn':
			return int(curseries[colname])
		elif colname=='percent':
			#tdata=QString(str(" %.2f%%"%(curser[each_col])))
			return 'test'	
		
	def UpdateDynamicColumns(self,symbolname,columnsdict):
		# update column content for symbol
		
		for columnname in columnsdict.keys():
			if columnname not in self.HeaderLabels:
				self.HeaderLabels[columnname]=columnname
				self.OnSetupColumns(self.HeaderLabels) # resetup column since changed
			
			colindex=self.HeaderLabels.keys().index(columnname)
			itemlist=self.findItems(QString(symbolname),Qt.MatchExactly,0)
			colvalue=columnsdict[columnname]
			if len(itemlist)>0:
				item=itemlist[0]
				# if item is found
				newitem=KStandardItem()
				newitem.setData(item.data(Qt.ForegroundRole),Qt.ForegroundRole)
				if isinstance(colvalue, float):
					colvalue=round(colvalue,3)
				newitem.setData(colvalue,Qt.DisplayRole)	
				self.setItem(item.row(), colindex, newitem);
			
	def UpdateSymbolList(self,symbolist):
	# build the model with specified fields

		self.cursymbolist=symbolist
		self.clear()
		mdframe=KQueryDB.QueryAllStocksStaticInfoBySymbolList(symbolist) # also get latest price
		self.OnSetupColumns(self.HeaderLabels)

		

		for rowindex in range(0,len(mdframe.index)): # iterate each row	
			curser=mdframe.iloc[rowindex]
			if len(curser)>0:
				each_index=0
				for each_col in self.HeaderLabels.values(): #iterate each col
					mitem=KStandardItem()
					mitem.setData(self.ColumnColor(curser,each_col),Qt.ForegroundRole)
					mitem.setData(self.ColumnValue(curser,each_col),Qt.DisplayRole)
					self.setItem(rowindex, each_index, mitem);
					each_index+=1
				rowindex+=1	
				
	def GetCurrentSymbolList(self):
	# get symbols displayed in current model
		return self.cursymbolist


		
		

	
